//
//  RootViewController.m
//  TVLive
//
//  Created by sid on 21/05/10.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "RootViewController.h"

#define kHostName @"www.apple.com"

@implementation RootViewController
@synthesize channels;
@synthesize internetConnectionStatus;
@synthesize remoteHostStatus;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad 
{
	[[Reachability sharedReachability] setHostName:kHostName];
	
	[[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES];
	
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(reachabilityChanged:) 
												 name:@"kNetworkReachabilityChangedNotification" 
											   object:nil];
    [self initStatus];

	tv = [[TVParser alloc] init];
    channels = [[NSMutableArray alloc] initWithObjects:@"Canal 24h", @"TVE 1", @"Cuatro", @"CNN+", @"Telecinco", @"LaSiete", @"Intereconomía", @"Teledeporte", @"CeutaTV", @"XarxaTV", nil];
	self.title = @"Live Spanish Channels";
	self.tableView.backgroundColor = [UIColor blackColor];
	self.navigationController.navigationBar.tintColor = [UIColor blackColor];
	
	UIButton* customButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
	
	[customButton addTarget:self
					 action:@selector(showInfo)
		   forControlEvents:UIControlEventTouchUpInside];
	
	UIBarButtonItem *infoButton = [[UIBarButtonItem alloc] initWithCustomView:customButton];
	
	self.navigationItem.rightBarButtonItem = infoButton;
	[super viewDidLoad];
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
	return [channels count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
	if (cell == nil) 
	{
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier] autorelease];
    }
    
	cell.textLabel.text = [channels objectAtIndex:indexPath.row];
	cell.accessoryType = UITableViewCellAccessoryNone;
	
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSString *selChannel = nil;
	
	if (indexPath.row == 0)
	{
		selChannel = [tv parseAddrAndGetVideoURL:@"http://iphonetv.es/24.html"];
	}
	else if	(indexPath.row == 1)
	{
		selChannel = [tv parseAddrAndGetVideoURL:@"http://iphonetv.es/rtve.html"];//@"http://iphonelive.rtve.es/stream1.m3u8";
	}
	else if (indexPath.row == 2)
	{
		selChannel = [tv parseAddrAndGetVideoURL:@"http://iphonetv.es/cuatro.html"];//@"http://xfootterx.is.livestream-api.com:1935/livestreamiphone/footter/playlist.m3u8";
	}
	else if (indexPath.row == 3)
	{
		selChannel = [tv parseAddrAndGetVideoURL:@"http://iphonetv.es/cnn.html"];//@"http://xcobrastex.is.livestream-api.com:1935/livestreamiphone/cobraste/playlist.m3u8";
	}
	else if (indexPath.row == 4)
	{
		selChannel =[tv parseAddrAndGetVideoURL:@"http://iphonetv.es/telecinco.html"];//@"http://iphone.xal.stream.flumotion.com/xal/iphone/main.m3u8";//@"http://82.165.130.134:1935/live2/myStream.sdp/playlist.m3u8";
	}
	else if (indexPath.row == 5)
	{
		selChannel = [tv parseAddrAndGetVideoURL:@"http://iphonetv.es/siete.html"];//@"http://xvistaalegrex.is.livestream-api.com:1935/livestreamiphone/vistaalegre/playlist.m3u8";
	}
	else if (indexPath.row == 6)
	{
		selChannel = [tv parseAddrAndGetVideoURL:@"http://iphonetv.es/inter.html"];//@"http://xkissespx.is.livestream-api.com:1935/livestreamiphone/kissesp/playlist.m3u8";
	}
	else if (indexPath.row == 7)
	{
		selChannel = [tv parseAddrAndGetVideoURL:@"http://iphonetv.es/rtve2.html"];//@"http://xldiphonex.is.livestream-api.com:1935/livestreamiphone/ldiphone/playlist.m3u8";
	}
	else if (indexPath.row == 8)
	{
		selChannel = [tv parseAddrAndGetVideoURL:@"http://iphonetv.es/rtvce.html"];
	}
	else if (indexPath.row == 9)
	{
		selChannel = [tv parseAddrAndGetVideoURL:@"http://iphonetv.es/xarxa.html"];
	}

	if (selChannel != nil)
	{
		NSURL *movieURL = [NSURL URLWithString:selChannel];
		if (movieURL)
		{
			if ([movieURL scheme])
			{
				TVLiveAppDelegate *appDelegate = (TVLiveAppDelegate *)[[UIApplication sharedApplication] delegate];

				[appDelegate initAndPlayMovie:movieURL];
				
				[self performSelector:@selector(deselectRowOfTable:) 
						   withObject:indexPath
						   afterDelay:1];
			}
		}
	}
	else
	{
		UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"Error!"
														message:@"Unexpected error!\nPlease try again later."
													   delegate:nil
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
		[error show];
		[error release];
		[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
	}
}

- (void)deselectRowOfTable:(NSIndexPath *)indexPath
{
	[self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void)showInfo
{
	FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:@"FlipsideView" bundle:nil];
	controller.delegate = self;
	controller.title = @"Credits";
	controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	[self presentModalViewController:controller animated:YES];
	
	[controller release];
}

- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller {
    
	[self dismissModalViewControllerAnimated:YES];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{	
	return NO;
}

#pragma mark -
#pragma mark REachability

- (void)reachabilityChanged:(NSNotification *)note
{
    [self updateStatus];
}

- (void)initStatus 
{
    self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus];
    self.internetConnectionStatus = [[Reachability sharedReachability] internetConnectionStatus];
}

- (void)updateStatus
{
    self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus];
    self.internetConnectionStatus    = [[Reachability sharedReachability] internetConnectionStatus];
    
	//NSLog(@"remote status = %d, internet status = %d", self.remoteHostStatus, self.internetConnectionStatus);
	
	if (self.internetConnectionStatus == NotReachable && self.remoteHostStatus == NotReachable) 
	{
			
		TVLiveAppDelegate *appDelegate = (TVLiveAppDelegate *)[[UIApplication sharedApplication] delegate];
		
		[appDelegate.moviePlayer stop];
		
		sleep(1);
		UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"Error!"
														message:@"Unexpected error!\nPlease try again later."
													   delegate:nil
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
		[error show];
		[error release];
	} 
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning 
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)dealloc 
{
    [super dealloc];
}

@end